import tornado.web

from .models import User,init_db

from utils.db import session,Base
from utils.faceid import face_register,face_login
class RegisterHandler(tornado.web.RequestHandler):
    def get(self, *args, **kwargs):
        error = ''
        self.render('register.html',error=error)
    def post(self, *args, **kwargs):
        face = self.get_argument('face_img')
        img = face.split(',')[-1]
        username = self.get_argument('username')
        password = self.get_argument('password')
        user = session.query(User).filter_by(username=username).first()
        if not user:
            users = User()
            users.username = username
            users.password = password
            session.add(users)
            session.commit()
            #调用百度人脸注册接口
            res = face_register(img,users.id)
            if res:
                self.redirect('/login/')
            else:
                session.delete(users)
                session.commit()
                self.redirect('/register/')
        else:
            error = '用户名已经存在'
            self.render('register.html',error=error)

class InitHandler(tornado.web.RequestHandler):
    def get(self, *args, **kwargs):
        init_db()
        self.write("创建表成功")

class LoginHandler(tornado.web.RequestHandler):
    def get(self, *args, **kwargs):
        self.render('login.html')

    def post(self, *args, **kwargs):
        face = self.get_argument('face_img')
        img = face.split(',')[-1]
        #调用百度人脸搜索接口
        res = face_login(img)
        if res:
            self.write("登录成功")
        else:
            self.redirect('/login/')
